﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using LDSP.BRL;
using BYFW.DAL;
using System.Data;
using LDSP.Util;
using LDSP.Constants;
using System.Drawing;
using LDSP.Helper;

namespace LDSP.UI.Admin
{
    public partial class MngCodification : LDSP.BRL.BaseSysAdminPage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                if (!IsPostBack)
                {
                    this.CheckQS();
                }
                if (this.RB())
                {
                    this.InitDataDynamicBefore();
                    if (!IsPostBack)
                    {
                        this.InitData();
                        this.BindTree();
                        this.InitTreeNodeSelection();

                        this.GetCondition();//刷新搜索条件，用来刷新LastID.#2
                        this.BindGrid();
                    }
                    this.InitDataDynamicAfter();
                }
            }
            catch (Exception ex)
            {
                this.HandlerException(ex);
            }
        }

        protected string TitleName = "法律法规";
        protected string ShortTitleName = "法规";
        protected string ReferenceName = "发布文号";
        private List<int> PDFIDs = new List<int>();

        private int col_chk = 0;
        private int col_index = 1;
        private int col_name = 2;
        private int col_category = 3;
        private int col_org = 4;
        private int col_referenceNumber = 5;
        private int col_release_DT = 6;
        private int col_implement_DT = 7;
        private int col_upload_DT = 8;
        private int col_is_valid = 9;
        private int col_summary = 10;
        private int col_keyitems = 11;
        private int col_invalid_list = 12;
        private int col_invalid_des = 13;
        private int col_pdf = 14;
        private int col_op = 15;

        protected Catalog m_catalog = null;

        protected int LastID
        {
            get { return this.GetVSInt("LastID"); }
            set
            {
                this.SetVS("LastID", value);
                m_catalog = null;
            }
        }
        protected Catalog Catalog
        {
            get
            {
                if (m_catalog == null)
                {
                    m_catalog = new Catalog();
                    if (LastID != 0)
                    {
                        m_catalog.GetProperties(LastID);
                    }
                }
                return m_catalog;
            }
        }
        protected DocType DocType
        {
            get { return (DocType)this.GetVSInt("DocType"); }
            set
            {
                this.SetVS("DocType", (int)value);
            }
        }
        protected bool ShowAll
        {
            get { return this.GetVSBool("ShowAll"); }
            set { this.SetVS("ShowAll", value); }
        }
        protected string EmptySearchStr
        {
            get { return this.GetVSString("EmptySearchStr"); }
            set { this.SetVS("EmptySearchStr", value); }
        }
        protected bool IsSuperAdmin { get { return this.LoginAdmin != null && this.LoginAdmin.IsSuper == true; } }

        /// <summary>
        /// 传入参数，设置过滤条件
        /// </summary>
        protected void SetSpecialPageInfo()
        {
            g_pageInfo.Direction = false;
            g_pageInfo.Sort = DocType == BRL.DocType.法律法规 ? "ReleaseDT" : "UploadDT";
            g_pageInfo.PageSize = GetPageSizeSetting();
            g_pageInfo.PageIndex = this.grd_list.PageIndex;
        }
        protected void CheckQS()
        {
            int docType = this.GetInt(this.Request.QueryString["docType"]);
            docType = docType != 1 ? 0 : 1;
            DocType = (DocType)docType;
        }
        protected bool RB()
        {
            return true;
        }
        protected void InitData()
        {
            //不缓存则清空页面信息
            if (!needCachePageInfo)
            {
                g_pageInfo.ClearPageInfo();
            }

            //高亮显示非默认搜索条件
            if (DocType == BRL.DocType.法律法规)
            {
                EmptySearchStr = Constants.EmptySearch.Codification;
            }
            else if (DocType == BRL.DocType.标准)
            {
                EmptySearchStr = Constants.EmptySearch.Standard;
            }
            UIHelper.SetDefaultFilterCondition(this.txt_name, EmptySearchStr);

            this.GetCondition();// 获取搜索条件，用来建立树状结构。#1
            this.SetSpecialPageInfo();
            this.BindDDLIsValid();
            this.BindDDLPageSize();
            this.JSShowModalDialog("cid=" + LastID, this.btn_add);
            this.JSShowModalDialog("cid=" + LastID, this.Button1);
        }

        private void BindDDLPageSize()
        {
            CommonControlInitial.InitialPageSize(this.ddl_pagesize);
            this.ddl_pagesize.SelectedValue = g_pageInfo.PageSize.ToString();
        }
        protected void InitDataDynamicBefore()
        {
            ShowColumns();
            if (DocType == BRL.DocType.标准)
            {
                this.TitleName = "标准";
                this.ShortTitleName = "标准";
                this.ReferenceName = "标准号";
                this.grd_list.Columns[col_referenceNumber].Visible = true;
                this.grd_list.Columns[col_keyitems].Visible = false;
            }
            this.grd_list.Columns[col_name].HeaderText = TitleName + "名称";
            this.grd_list.Columns[col_referenceNumber].HeaderText = ReferenceName;
            this.grd_list.Columns[col_summary].HeaderText = ShortTitleName + "概述";

            UIHelper.SyncGridHeadColumn(grd_list, grd_list_head);

            //如果不是超级系统管理员，则不可以发送邮件。
            this.btnMailSender.Visible = IsSuperAdmin;
            this.btnMailSender0.Visible = IsSuperAdmin;
        }

        private void ShowColumns()
        {
            //法规需要显示的字段: 多选框，名称，       法规概述，关键条款。
            //标准要显示的字段，  多选框，名称，标准号，标准概述，       。
            //this.grd_list.Columns[0].Visible = ShowAll;
            this.grd_list.Columns[col_index].Visible = ShowAll;
            //this.grd_list.Columns[2].Visible = ShowAll;
            this.grd_list.Columns[col_category].Visible = ShowAll;
            this.grd_list.Columns[col_org].Visible = ShowAll;
            this.grd_list.Columns[col_referenceNumber].Visible = ShowAll;
            this.grd_list.Columns[col_release_DT].Visible = ShowAll;
            this.grd_list.Columns[col_implement_DT].Visible = ShowAll;
            this.grd_list.Columns[col_upload_DT].Visible = ShowAll;
            this.grd_list.Columns[col_is_valid].Visible = ShowAll;
            //this.grd_list.Columns[10].Visible = ShowAll;
            this.grd_list.Columns[col_keyitems].Visible = ShowAll;
            //this.grd_list.Columns[12].Visible = ShowAll;
            this.grd_list.Columns[col_invalid_des].Visible = ShowAll;
            this.grd_list.Columns[col_invalid_list].Visible = ShowAll;


        }
        protected void InitDataDynamicAfter()
        {
            this.JSSetDateTimeReadOnly(this.txt_releaseStartDT.ClientID);
            this.JSSetDateTimeReadOnly(this.txt_releaseEndDT.ClientID);
            this.JSSetDateTimeReadOnly(this.txt_implementStartDT.ClientID);
            this.JSSetDateTimeReadOnly(this.txt_implementEndDT.ClientID);
            this.JSSetDateTimeReadOnly(this.txt_uploadStartDT.ClientID);
            this.JSSetDateTimeReadOnly(this.txt_uploadEndDT.ClientID);

            UIHelper.SetDefaultFilterCondition(this.txt_name, EmptySearchStr, false);
        }
        protected void BindGrid()
        {
            //更新关键字表,以便智能提示.
            string keyword = this.txt_name.Text.Trim();
            if (EmptySearchStr.Equals(keyword))
            {
                keyword = "";
            }
            if (!string.IsNullOrEmpty(keyword))
            {
                new SearchKeywords().IncreaseWordsCount(keyword);
            }

            DataTable dt = null;

            this.grd_list.PageSize = g_pageInfo.PageSize;
            this.grd_list.PageIndex = g_pageInfo.PageIndex;

            //组合关键字命中结果的sort table语句.
            string sortDBData = "viewTimes desc, nameTimes desc, ";
            sortDBData += DocType == BRL.DocType.法律法规 ? "" : "ReferenceNumber desc,";
            sortDBData += "SummaryTimes desc";

            string cacaulatedSelectFields = GetCaculatedSelectMulti(keyword, "t.name", "t.Summary", DocType == BRL.DocType.法律法规 ? "" : "t.ReferenceNumber");
            if (LastID == 0 && !LoginAdmin.IsSuper)
            {
                dt = BYFW.SFL.CommonOP.SortedTable(new Codification().GetRecordsBySystemUserID(LoginAdmin.ID, g_pageInfo.ConditionWhere, cacaulatedSelectFields), sortDBData, g_pageInfo.GetSortExpression());
            }
            else
            {
                dt = BYFW.SFL.CommonOP.SortedTable(new Codification().GetRecordsForSystemAdmin(g_pageInfo.ConditionWhere, cacaulatedSelectFields), sortDBData, g_pageInfo.GetSortExpression());
            }
            this.grd_list.DataSource = dt;
            this.grd_list.DataBind();

            SavePageSizeSetting();

            UIHelper.BindEmptyHeader(grd_list_head, dt);

            this.TotalRecords.Text = LDSP.Helper.StringUtil.GetSearchText(dt.Rows.Count);
        }
        protected void BindTree()
        {
            this.tre_obj.Nodes.Clear();

            TreeNode all = new TreeNode();
            all.Text = "所有";
            all.Value = "0";
            this.tre_obj.Nodes.Add(all);

            List<Catalog> rootCatalogs = new Catalog().GetListRootByDefault();
            for (int i = 0; i < rootCatalogs.Count; i++)
            {
                if (HaveCatalogPermission(rootCatalogs[i].ID))
                {
                    TreeNode nd = new TreeNode();
                    nd.Text = rootCatalogs[i].Name;
                    nd.Value = rootCatalogs[i].ID.ToString();
                    all.ChildNodes.Add(nd);
                    this.BindTreeAssis(nd, rootCatalogs[i].ID);
                }
            }
            //将Text信息记录在Value上，用于更新Number时用
            UIHelper.UpdateTreeNodeValueWithText(all);
            //计算tree上的数量.
            this.UpdateTreeNumber();

            all.CollapseAll();
        }
        protected void BindTreeAssis(TreeNode parent, int parentID)
        {
            List<Catalog> catalogs = new Catalog().GetListByParentID(parentID);
            for (int i = 0; i < catalogs.Count; i++)
            {
                if (HaveCatalogPermission(catalogs[i].ID))
                {
                    TreeNode nd = new TreeNode();
                    nd.Text = catalogs[i].Name;
                    nd.Value = catalogs[i].ID.ToString();
                    parent.ChildNodes.Add(nd);
                    this.BindTreeAssis(nd, catalogs[i].ID);
                }
            }
        }
        protected void InitTreeNodeSelection()
        {
            if (this.tre_obj.Nodes.Count > 0)
            {
                TreeNode cachedNode = this.InitCatalogTreeSelectedNodeForCache(this.tre_obj.Nodes);
                if (cachedNode != null)
                {
                    cachedNode.Select();
                    this.ExpandParentsNode(cachedNode);
                }
                else
                {
                    this.tre_obj.Nodes[0].Select();
                }
                this.LastID = UIHelper.GetTreeNodeIDFromValue(this.tre_obj.SelectedNode);
                this.btn_add.Enabled = LastID > 0;
                this.Button1.Enabled = LastID > 0;
            }
        }
        protected void UpdateTreeNumber()
        {
            for (int i = 0; i < this.tre_obj.Nodes.Count; i++)
            {
                new AdminTreeNodeModifer(DocType).CaculateNumber(this.tre_obj.Nodes[i], UIHelper.GetTreeNumberCondition(g_pageInfo));
            }
        }

        protected void BindDDLIsValid()
        {
            this.ddl_isValid.Items.Clear();
            this.ddl_isValid.Items.Add("--请选择--");
            this.ddl_isValid.Items.Add(new ListItem("无效", "0"));
            this.ddl_isValid.Items.Add(new ListItem("有效", "1"));
            try
            {
                this.ddl_isValid.SelectedIndex = 0;
            }
            catch { }

        }

        protected void GetCondition()
        {
            string cond = "";
            cond = this.AppendCondition(cond, DefaultDB.GetSQLNormalCondition("t.enterpriseID", EDataType.Int, "0", "=", false), true);
            cond = this.AppendCondition(cond, DefaultDB.GetSQLNormalCondition("t.docType", EDataType.Int, ((int)DocType).ToString(), "=", false), true);
            string nameCond = this.txt_name.Text.Trim();
            if (nameCond != ""
                && nameCond != EmptySearchStr)
            {
                string tempCond = this.AppendConditionMulti("", nameCond, true, "t.name", "t.Summary", DocType == BRL.DocType.法律法规 ? "" : "t.ReferenceNumber");
                PDFIDs = new List<int>();
                if (chb_pdf.Checked)
                {
                    nameCond = UIHelper.CombindBlank(nameCond);
                    nameCond = nameCond.Replace(" ", " and ");
                    tempCond = this.AppendCondition(tempCond, string.Format("contains(t.pdfcontent,'{0}')", nameCond), false);
                    PDFIDs = UIHelper.GetPDFFilterIDsForCodification(nameCond);
                }
                cond = this.AppendCondition(cond, tempCond, true);
                this.SetHighlight(nameCond);
            }
            if (this.ddl_isValid.SelectedIndex > 0)
            {
                cond = this.AppendCondition(cond, DefaultDB.GetSQLNormalCondition("t.isValid", EDataType.Bool, this.ddl_isValid.SelectedValue, "=", false), true);
            }
            if (this.txt_releaseStartDT.Text.Trim() != "")
            {
                cond = this.AppendCondition(cond, DefaultDB.GetSQLNormalCondition("t.releaseDT", EDataType.Date, this.txt_releaseStartDT.Text, ">=", false), true);
            }
            if (this.txt_releaseEndDT.Text.Trim() != "")
            {
                cond = this.AppendCondition(cond, DefaultDB.GetSQLNormalCondition("t.releaseDT", EDataType.Date, this.txt_releaseEndDT.Text, "<=", false), true);
            }
            if (this.txt_implementStartDT.Text.Trim() != "")
            {
                cond = this.AppendCondition(cond, DefaultDB.GetSQLNormalCondition("t.implementDT", EDataType.Date, this.txt_implementStartDT.Text, ">=", false), true);
            }
            if (this.txt_implementEndDT.Text.Trim() != "")
            {
                cond = this.AppendCondition(cond, DefaultDB.GetSQLNormalCondition("t.implementDT", EDataType.Date, this.txt_implementEndDT.Text, "<=", false), true);
            }
            if (this.txt_uploadStartDT.Text.Trim() != "")
            {
                cond = this.AppendCondition(cond, DefaultDB.GetSQLNormalCondition("t.uploadDT", EDataType.Date, this.txt_uploadStartDT.Text, ">=", false), true);
            }
            if (this.txt_uploadEndDT.Text.Trim() != "")
            {
                cond = this.AppendCondition(cond, DefaultDB.GetSQLNormalCondition("t.uploadDT", EDataType.Date, this.txt_uploadEndDT.Text, "<=", false), true);
            }
            UIHelper.SaveTreeNumberCondition(g_pageInfo, cond);
            if (LastID > 0)
            {
                cond = this.AppendCondition(cond, DefaultDB.GetSQLNormalCondition("t2.fullpath", EDataType.String, Catalog.FullPath + "%", "like", false), true);
            }
            g_pageInfo.Condition = cond;
        }

        private void JSShowModalDialog(string arg, WebControl ctrl)
        {
            this.JSShowDialog("AddCodification.aspx?docType=" + (int)DocType + "&" + arg, 1000, 900, ctrl, null, null, null, null, null, null, null, true, null, null, null, null, null);
        }

        protected void btn_add_Click(object sender, EventArgs e)
        {
            try
            {
                this.BindTree();
                this.InitTreeNodeSelection();
                this.BindGrid();
            }
            catch (Exception ex)
            {
                this.HandlerException(ex);
            }
        }

        protected void btn_delete_Click(object sender, EventArgs e)
        {
            try
            {
                this.DeleteCheckedInGrid<Codification>(this.grd_list);

                this.BindTree();
                this.InitTreeNodeSelection();
                this.BindGrid();
            }
            catch (Exception ex)
            {
                this.HandlerException(ex);
            }
        }
        protected void btn_search_Click(object sender, EventArgs e)
        {
            try
            {
                this.GetCondition();
                this.BindGrid();
                this.UpdateTreeNumber();
            }
            catch (Exception ex)
            {
                this.HandlerException(ex);
            }
        }
        protected void btn_export_Click(object sender, EventArgs e)
        {
            //Collect codifications.
            IDictionary<string, IList<Codification>> codifications = new Dictionary<string, IList<Codification>>();
            List<int> ids = this.GetAllCheckedItems(this.hid_docIDs);
            for (int i = 0; i < ids.Count; i++)
            {
                Codification ett = new Codification();
                ett.GetProperties(ids[i]);

                if (ett.Catalog != null)
                {
                    if (codifications.ContainsKey(ett.Catalog.Name))
                    {
                        codifications[ett.Catalog.Name].Add(ett);
                    }
                    else
                    {
                        IList<Codification> codificationList = new List<Codification>();
                        codificationList.Add(ett);
                        codifications.Add(ett.Catalog.Name, codificationList);
                    }
                }
            }

            CodificationExportBase<Catalog, Codification> export = null;
            string templateName = string.Empty;
            if (DocType == BRL.DocType.法律法规)
            {
                export = new CodificationExport();
                templateName = "finalCodification.xls";
            }
            else
            {
                export = new StandardExport();
                templateName = "finalStandard.xls";
            }

            //Get data table for codifications.
            IDictionary<string, DataTable> tables = new Dictionary<string, DataTable>();
            foreach (string key in codifications.Keys)
            {
                DataTable dt = export.ConstructDT(codifications[key]);
                tables.Add(key, dt);
            }

            //Export.
            export.Export(tables, Server, templateName);
        }

        protected void grd_list_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            try
            {
                int id = this.GetInt(e.CommandArgument.ToString());
                Codification ett = new Codification();
                ett.GetProperties(id);
                if (e.CommandName == "downloadItem")
                {
                    this.StartDownload(ett.ID, ett.DocType);

                    //记录一次查看
                    ett.ViewTimes++;
                    ett.Update();
                }
                else if (e.CommandName == "deleteItem")
                {
                    ett.Delete();
                }
                this.BindGrid();
            }
            catch (Exception ex)
            {
                this.HandlerException(ex);
            }
        }
        protected void grd_list_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            try
            {
                if (e.Row.RowType == DataControlRowType.DataRow)
                {
                    Codification ett = new Codification();
                    ett.GetProperties(((DataRowView)e.Row.DataItem).Row);
                    this.ShowSequenceNumber(e.Row, 1);

                    WebControl c = (WebControl)e.Row.FindControl("LinkButton2");
                    this.JSShowModalDialog("id=" + ett.ID, c);

                    CheckBox chb = (CheckBox)e.Row.FindControl("chb");
                    chb.Attributes["docid"] = ett.ID.ToString();
                    if (this.MultiPageIncludeCheckedId(this.hid_docIDs, ett.ID))
                    {
                        chb.Checked = true;
                    }

                    e.Row.Cells[col_category].Text = ett.Category.Name;
                    e.Row.Cells[col_release_DT].Text = this.FormatDT(ett.ReleaseDT);
                    e.Row.Cells[col_implement_DT].Text = this.FormatDT(ett.ImplementDT);
                    e.Row.Cells[col_upload_DT].Text = this.FormatDT(ett.UploadDT);
                    e.Row.Cells[col_is_valid].Text = ett.IsValid ? "是" : "否";
                    e.Row.Cells[col_summary].Text = ett.Summary.Replace("\n", "</br>");
                    e.Row.Cells[col_keyitems].Text = ett.KeyItems.Replace("\n", "</br>");
                    e.Row.Cells[col_invalid_des].Text = ett.InvalidDescription.Replace("\n", "</br>");
                    e.Row.Cells[col_invalid_list].Text = ett.InvalidList.Replace("\n", "</br>");

                    UIHelper.AppendEmptyLine(e.Row, col_summary);

                    if (PDFIDs.Contains(ett.ID))
                    {
                        e.Row.Cells[col_pdf].Text = "包含";
                    }

                    //设置失效法规为红色字体.
                    if (ett.IsValid == false)
                    {
                        e.Row.ForeColor = Color.Red;
                    }

                    //设置title
                    if (ShowAll)
                    {
                        e.Row.ToolTip = string.Empty;
                    }
                    else
                    {
                        e.Row.ToolTip = StringUtil.ConstructTitle(ett);
                    }

                    this.HighlightMulti(e.Row, col_name, col_org, col_referenceNumber, col_summary, col_keyitems, col_invalid_des);
                }
            }
            catch (Exception ex)
            {
                this.HandlerException(ex);
            }
        }
        protected void grd_list_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            try
            {
                g_pageInfo.PageIndex = e.NewPageIndex;
                this.GetCondition();
                this.BindGrid();
            }
            catch (Exception ex)
            {
                this.HandlerException(ex);
            }
        }
        protected void grd_list_Sorting(object sender, GridViewSortEventArgs e)
        {
            try
            {
                if (g_pageInfo.Sort == e.SortExpression)
                {
                    g_pageInfo.Direction = !g_pageInfo.Direction;
                }
                else
                {
                    g_pageInfo.Direction = true;
                }
                g_pageInfo.Sort = e.SortExpression;
                this.BindGrid();
            }
            catch (Exception ex)
            {
                this.HandlerException(ex);
            }
        }
        protected void tre_obj_SelectedNodeChanged(object sender, EventArgs e)
        {
            LastID = UIHelper.GetTreeNodeIDFromValue(this.tre_obj.SelectedNode);
            this.btn_add.Enabled = LastID > 0;
            this.Button1.Enabled = LastID > 0;
            this.GetCondition();
            this.BindGrid();
            this.JSShowModalDialog("cid=" + LastID, this.btn_add);
            this.JSShowModalDialog("cid=" + LastID, this.Button1);
            this.SetSessionData(SK_CachedCatalogID, LastID);
        }
        protected void ddl_pageSize_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                g_pageInfo.PageSize = this.GetInt(this.ddl_pagesize.SelectedValue);
                this.BindGrid();
            }
            catch (Exception ex)
            {
                this.HandlerException(ex);
            }
        }

        protected void btnMailSender_Click(object sender, EventArgs e)
        {
            //Collect codifications.
            IList<Codification> codifications = new List<Codification>();
            List<int> ids = this.GetAllCheckedItems(this.hid_docIDs);
            if (ids.Count == 0)
            {
                this.JSAlert("您没有选中的法规/标准！");
            }
            else
            {
                string idStr = string.Empty;
                foreach (int id in ids)
                {
                    idStr += id.ToString() + "a";
                }

                this.JSOpenWindow("EmailSender1.aspx?MailCodification=" + idStr, 750, 650, null, null, null, 100, 0, false, false, false, false, false, false, true, false, false, false);
            }
        }
    }

}